package com.demo.juc.pci;

/**
 * @Author: jxm
 * @Description: 生产者消费者问题 Sychronized 版本
 * <p>
 * 线程之间的通信问题：生产者和消费者问题
 * 线程交替执行：A B操作同一个变量 num = 0
 * A num+1
 * B num-1
 * @Date: 2024-2-6 10:52
 * @Version: 1.0
 */
public class ProductAndConsumerTest1 {


    /**
     * 线程之间的通信问题：生产者和消费者问题
     * 线程交替执行：A B操作同一个变量 num = 0
     * A num+1
     * B num-1
     */
    public static void main(String[] args) {
        Date date = new Date();
        //执行+1
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    date.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();
        //执行-1
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    date.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
    }
}

//判断等待，业务，通知
class Date {//数字 资源类

    private int number = 0;

    //+1
    public synchronized void increment() throws InterruptedException {
        while (number != 0) {
            //等待
            this.wait();
        }
        number++;
        //通知其他线程，我+1完毕
        System.out.println(Thread.currentThread().getName() + "=>" + number);
        this.notifyAll();
    }

    //-1
    public synchronized void decrement() throws InterruptedException {
        while (number == 0) {
            //等待
            this.wait();
        }
        number--;
        //通知其他线程，我-1完毕
        System.out.println(Thread.currentThread().getName() + "=>" + number);
        this.notifyAll();
    }


}
